﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TransformerManager.Shared.Helper
{
    public class PaginationList<T> : List<T>
    {
        public int TotalPages { get; private set; }
        public int TotalCount { get; private set; }
        public bool HasPrevious => CurrentPage > 1;
        public bool HasNext => CurrentPage < TotalPages;
        public int CurrentPage;
        public int PageSize;

        public PaginationList(int totalCount, int currentPage, int pageSize, List<T> items)
        {
            CurrentPage = currentPage;
            PageSize = pageSize;
            AddRange(items);
            TotalCount = totalCount;
            TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
        }

        public static async Task<PaginationList<T>> CreateAsync(
            int currentPage,
            int pageSize,
            IQueryable<T> result)
        {
            // 获取数据总量
            var totalCount = await result.CountAsync();
            // 分页逻辑
            var skipNum = (currentPage - 1) * pageSize;
            result = result.Skip(skipNum).Take(pageSize); // 先跳过skipNum数量的数据，然后提取定义好的pageSize大小的数据

            var items = await result.ToListAsync();

            return new PaginationList<T>(totalCount, currentPage, pageSize, items);
        }
    }
}
